package com.woniuxy.happylife.controller;

import com.woniuxy.happylife.entity.ResponseEntity;
import com.woniuxy.happylife.util.QiniuCloudUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Classname Img
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/2/18 12:11
 * @Created by hang
 */
@RestController
@CrossOrigin
@RequestMapping("/img")
public class ImgController {
    @RequestMapping(value="/uploadImg", method=RequestMethod.POST)
    public ResponseEntity uploadImg(@RequestParam MultipartFile image) {
        if (image.isEmpty()) {
            return new ResponseEntity<>(403,"图片为空","");
        }
        try {
            byte[] bytes = image.getBytes();
            String imageName = image.getOriginalFilename();
            ResponseEntity result = new ResponseEntity();
            QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
            try {
                //使用base64方式上传到七牛云
                String url = qiniuUtil.put64image(bytes, imageName);
                String imgUrl = "http://r7hvave5i.hn-bkt.clouddn.com/" + imageName;
                result.setCode(200);
                result.setMsg("文件上传成功,访问路径生成成功");
                result.setData(imgUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        } catch (IOException e) {
            return new ResponseEntity(500,"文件上传发生异常","");
        }
    }

}
